package com.xugongzhang.unsafeDemo;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author X
 * @date 2022/7/26 0:24
 */
public class ABADemo {
    public static void main(String[] args) {
        Book javaBook = new Book(1, "javaBook");
        // 入参为共享变量和版本号
        AtomicStampedReference<Book> stampedReference = new AtomicStampedReference<>(javaBook, 1);
        System.out.println(stampedReference.getReference() + "---" + stampedReference.getStamp());
        Book mysqlBook = new Book(2, "mysqlBook");
        boolean b;
        // 参数为期望值，更新值，期望版本号，更新版本号
        b = stampedReference.compareAndSet(javaBook, mysqlBook, stampedReference.getStamp(), stampedReference.getStamp() + 1);
        System.out.println(stampedReference.getReference() + "---" + stampedReference.getStamp());
        b = stampedReference.compareAndSet(mysqlBook, javaBook, stampedReference.getStamp(), stampedReference.getStamp() + 1);
        System.out.println(stampedReference.getReference() + "---" + stampedReference.getStamp());
    }
}

@Getter
@Setter
@AllArgsConstructor
@ToString
class Book {
    private Integer id;
    private String name;
}
